<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';

import type { ImageCaptchaResp } from '#/api';

import { computed, onMounted, ref, useTemplateRef } from 'vue';

import { AuthenticationLogin, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { encryptByRsa } from '@vben/utils';

import { omit } from 'lodash-es';

import { getImageCaptcha } from '#/api';
import { useAuthStore } from '#/store';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();

// 验证码信息
const imageCaptchaInfo = ref<ImageCaptchaResp>({
  isEnabled: false,
  img: '',
  uuid: '',
  expireTime: 0,
});
// 获取验证码
const loadImageCaptcha = async () => {
  imageCaptchaInfo.value = await getImageCaptcha();
};
const authenticationLoginRef = useTemplateRef('authenticationLoginRef');
onMounted(async () => {
  await loadImageCaptcha();
});

// 登录表单列
const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.usernameTip'),
      },
      dependencies: {
        triggerFields: ['selectAccount'],
      },
      defaultValue: 'admin',
      fieldName: 'username',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.password'),
      },
      defaultValue: 'admin123',
      fieldName: 'password',
      label: $t('authentication.password'),
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
    },
    {
      component: 'InputCaptcha',
      fieldName: 'captcha',
      rules: z
        .string()
        .min(1, { message: $t('authentication.verifyRequiredTip') }),
      componentProps: {
        captchaImgBase64: imageCaptchaInfo.value.img,
        class: 'focus:border-primary',
        placeholder: $t('authentication.code'),
        onCaptchaClick: () => loadImageCaptcha(),
      },
      dependencies: {
        if: () => imageCaptchaInfo.value.isEnabled,
        triggerFields: [''],
      },
    },
  ];
});
// 账号登录提交
const handleAccountLogin = async (formParams: any) => {
  try {
    const accountLoginReq = omit(formParams, ['uuid']);
    // 验证码
    if (imageCaptchaInfo.value.isEnabled) {
      accountLoginReq.uuid = imageCaptchaInfo.value.uuid;
    }
    accountLoginReq.password = encryptByRsa(accountLoginReq.password);
    await authStore.authLogin(accountLoginReq);
  } catch {
    authenticationLoginRef.value?.getFormApi().setFieldValue('captcha', '');
    await loadImageCaptcha();
  }
};
</script>

<template>
  <AuthenticationLogin
    ref="authenticationLoginRef"
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    @submit="handleAccountLogin"
  />
</template>
